import antv, {message} from 'ant-design-vue'
import md5 from "md5";
import {setupApp} from "~/logic/common-setup";
import RenderOption, {InsertType} from "~/utils/render/renderOption";
import RenderOptions from "~/utils/render/renderOptions";
import RequestInterception from "~/utils/RequestInterception";
import mitt from "mitt";
// @ts-ignore
import VueSortable from "vue3-sortablejs";

const InterceptionState: any = {};
const switchMap = {
    SYCM: 'XCSJ_SYCM_DISABLED',
    TAOBAO: 'XCSJ_TAOBAO_DISABLED',
};
export const RenderRenderOptions = () => {
    RenderOptions.map((option: RenderOption) => {
        if (location.href.includes('//sycm.taobao.com')) {
            if (localStorage.getItem(switchMap.SYCM) == 'true' && !option.noCheckSwitch) {
                return;
            }
        }
        const id = 'XCSJ_CONTAINER_' + md5(option.url + '__' + option.containerSelector + `[${option?.key || 'null'}]`);
        if (typeof option.interceptions === 'object' && option.interceptions.length > 0 && typeof InterceptionState[id] === "undefined") {
            InterceptionState[id] = new RequestInterception(option.interceptions);
        }
        if (location.href.includes(option.url) && document.querySelector(option.containerSelector) && !document.querySelector('#' + id) && (typeof option.condition == 'undefined' || option.condition())) {
            const dom = document.createElement('div');
            dom.id = id;
            if (typeof option.style == "object") {
                for (const styleKey in option.style) {
                    // @ts-ignore
                    dom.style[styleKey] = option.style[styleKey];
                }
            }
            const container = document.querySelector(option.containerSelector);
            if (option.insertType == InsertType.append) {
                container?.append(dom);
            } else if (option.insertType == InsertType.prepend) {
                container?.prepend(dom);
            }
            let app = createApp(option.component);
            app.use(antv)
            if (typeof InterceptionState[id] !== 'undefined') {
                app.config.globalProperties.$req = InterceptionState[id];
            }
            // @ts-ignore
            app.config.globalProperties.$eventBus = new mitt();
            // 把id注入到app
            app.config.globalProperties.$id = id;
            app.provide('ID', id);
            app.provide('option', option);
            if (typeof option.customApp == 'function') {
                app = option.customApp(app);
            }
            setupApp(app);
            app.use(VueSortable);
            app.mount(dom);
        }
    });
}

